package org.tulkas.robot.base;

import java.util.Properties;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
@Service
public class AppDataManager {
	public static final String DATA_DB_DIR = "data";

	private ComboPooledDataSource datasource = null;
	private static Logger logger = LoggerFactory
			.getLogger(AppDataManager.class);

	@PostConstruct
	public void init() {
		String dbPath = GlobalConfig.getInstance().getHomePath() + "/"
				+ DATA_DB_DIR;
		boolean stat = PersistenceHelper.ensureDerbyDBCreated(dbPath);
		if (stat) {
			logger.info("Found Tulkas app database in [" + dbPath + "]");
		} else {
			logger.info("Tulkas app database not exist in [" + dbPath
					+ "]. Create it.");
		}

		logger.info("Initialize Tulkas app datasource.");
		Properties props = GlobalConfig.getInstance().getSubProperties(
				"app.datasource.");
		props.setProperty("jdbcUrl", PersistenceHelper.getDerbyJdbcUrl(dbPath));
		datasource = new ComboPooledDataSource();
		PersistenceHelper.initC3p0DataSource(datasource, props);

		logger.trace("Tulkas app datasource: {}", datasource);
	}

	public ComboPooledDataSource getDatasource() {
		return datasource;
	}
}
